package com.yimi.yinhepda.views.load_module;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.liji.imagezoom.util.ImageZoom;
import com.pda.uce.commom.util.LogUtil;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.callbacks.UICallBack;
import com.pda.ym.entity.bean.CarPlanTaskEntity;
import com.pda.ym.entity.bean.ImageInfo;
import com.pda.ym.entity.bean.ImageInfoResponse;
import com.pda.ym.entity.bean.LoadBillTaskEntity;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.ActivityStack;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.ym.utils.StringUtils;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.ScanSealSignAdapter;
import com.yimi.yinhepda.adapter.RecycleAdapter.SealSignTakePhotoAdapter;
import com.yimi.yinhepda.adapter.RecycleAdapter.SelectSealSignStowageAdapter;
import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.entity.bean.ScanSealSignEntity;
import com.yimi.yinhepda.entity.bean.SelectSealSignStowage;
import com.yimi.yinhepda.entity.bean.TakePhotoEntity;
import com.yimi.yinhepda.entity.request.QueryLoadDetailRequest;
import com.yimi.yinhepda.entity.request.SetOutSealCarRequest;
import com.yimi.yinhepda.entity.response.QueryFCPhotographDictResponse;
import com.yimi.yinhepda.entity.response.QueryLoadDetailBillcode;
import com.yimi.yinhepda.entity.response.QueryLoadDetailChildBillcode;
import com.yimi.yinhepda.entity.response.QueryLoadDetailResponse;
import com.yimi.yinhepda.utils.BitmapUtils;
import com.yimi.yinhepda.utils.Common;
import com.yimi.yinhepda.utils.GlideImageLoader;
import com.yimi.yinhepda.utils.PermissionUtils;
import com.pda.ym.utils.SoundVibratorManager;
import com.yimi.yinhepda.utils.TipHelper;
import com.yimi.yinhepda.views.offline.load.OffLineLoadCacheActivity;
import com.yimi.yinhepda.views.offline.unload.OffLineUnLoadCacheActivity;
import com.yimi.yinhepda.views.offline.unload.OffLineUnloadActivity;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 扫描封签界面
 *
 * @author 000432
 * @date 2018/6/4 0004
 */
@Route(path = Constants.YM_SCAN_SEAL_SIGN_ACTIVITY)
public class ScanSealSignActivity extends BaseActivity
        implements CommonViewHolder.onItemCommonClickListener {

    private RecyclerView sealSignListView;
    private RecyclerView rvTakePhoto;
    private ScanSealSignAdapter mAdapter;
    private SealSignTakePhotoAdapter takePhotoAdapter;
    private List<TakePhotoEntity> takePhotoEntities;
    private List<ScanSealSignEntity> mScanSealSignEntities;
    private ScanSealSignEntity mScanSealSignEntity;
    private boolean isGalleryConfigPick = false;
    private final String[] PERMISSIONS = new String[]{Manifest.permission.CAMERA};
    private final int REQUEST_CODE_PERMISSIONS = 100;
    /**
     * 上传图片的key
     */
    private String imageKey = "";
    /**
     * 选择图片路径
     */
    private List<String> pickPic;
    /**
     * 图片选择器
     */
    private GalleryConfig galleryConfig;
    /**
     * 配载单号
     */
    @Autowired(name = "stowageNos")
    public String mStowageNos;
    /**
     * 车牌号
     */
    @Autowired(name = "carNos")
    public String mCarNos;
    /**
     * 运输方式：1-trunk_line干线,2-branch_line支线,3-car_load:整车
     */
    @Autowired(name = "bizTypeCodes")
    public String mBizTypeCodes;
    /**
     * 下一站code
     */
    @Autowired(name = "nextStationCodes")
    public String mNextStationCodes;
    /**
     * 下一站名称
     */
    @Autowired(name = "nextStation")
    public String mNextStation;
    /**
     * 发车计划任务集合
     */
    @Autowired(name = "carPlanTaskList")
    public List<CarPlanTaskEntity> mCarPlanTaskEntityList;
    @Autowired(name = "fromFitActivity")
    public boolean fromFitActivity;
    /**
     * 是否出发封车界面传递过来
     */
    private boolean mFromSetOutActivity;
    /**
     * 已封车配载单暂存list
     */
    private List<String> mStowageNoList;
    private Dialog mSelectStowageDialog;
    /**
     * 离线装车任务号
     */
    private String offlineTaskNo;
    /**
     * 离线装车的车牌号
     */
    private String carPlateNo;
    /**
     * 装车类型：1-离线装车类型,2-离线卸车，3-单独封车
     */
    private int loadType;
    /**
     * 封车解封按钮
     */
    private Button btnSealCar;
    /**
     * 本地任务号
     */
    private String mTaskNo;

    public ScanSealSignActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return "扫描封签界面";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_seal_sign);

        initView();
        initData();
    }

    private void initView() {
        sealSignListView = findViewById(R.id.rv_seal_sign_list);
        rvTakePhoto = findViewById(R.id.rv_take_photo);
        findViewById(R.id.btn_back).setOnClickListener(this);
        btnSealCar = findViewById(R.id.btn_sealCar);
        btnSealCar.setOnClickListener(this);
        findViewById(R.id.ib_delete).setOnClickListener(this);
    }

    private void initData() {
        ARouter.getInstance().inject(this);
        mTaskNo = getIntent().getStringExtra("taskNo");
        //装车类型：1-离线装车类型,2-离线卸车，3-单独封车
        loadType = getIntent().getIntExtra("loadType", -1);
        if (loadType == 1 || loadType == 2 || loadType == 3) {
            offlineTaskNo = getIntent().getStringExtra("offlineTaskNo");
            carPlateNo = getIntent().getStringExtra("carPlateNo");
            //运输方式
            mBizTypeCodes = getIntent().getStringExtra("lineType");
            if (loadType == 2) {
                btnSealCar.setText("解封");
            }
            rvTakePhoto.setVisibility(View.GONE);
        } else {
            if (!fromFitActivity) {
                //配载单号
                mStowageNos = getIntent().getStringExtra("stowageNos");
                //车牌号
                mCarNos = getIntent().getStringExtra("carNos");
                //运输方式
                mBizTypeCodes = getIntent().getStringExtra("bizTypeCodes");
                //下一站code
                mNextStationCodes = getIntent().getStringExtra("nextStationCodes");
                //下一站名称
                mNextStation = getIntent().getStringExtra("nextStation");
                //发车计划任务集合
                mCarPlanTaskEntityList = (List<CarPlanTaskEntity>) getIntent().getSerializableExtra("carPlanTaskList");

                //是否修改标签标志
                mFromSetOutActivity = getIntent().getBooleanExtra("fromSetOutActivity", false);
                rvTakePhoto.setVisibility(View.VISIBLE);
            }
        }

        mStowageNoList = new ArrayList<>();
        mScanSealSignEntities = new ArrayList<>();
        //封签列表适配器
        mAdapter = new ScanSealSignAdapter(this, mScanSealSignEntities, this);
        sealSignListView.setLayoutManager(
                new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        sealSignListView.setAdapter(mAdapter);

        //图片适配器
        takePhotoEntities = new ArrayList<>();
        takePhotoEntities.add(new TakePhotoEntity(BitmapFactory.decodeResource(getResources(), R.drawable.btn_take_photo_selector)));
        takePhotoAdapter = new SealSignTakePhotoAdapter(this, takePhotoEntities, new CommonViewHolder.onItemCommonClickListener() {
            @Override
            public void onItemClickListener(int position) {
                if (position == takePhotoEntities.size() - 1) {
                    checkPersmisson();
                } else {
                    //图片展示
                    ImageZoom.show(ScanSealSignActivity.this, position, pickPic);
                }
            }

            @Override
            public void onItemLongClickListener(final int position) {
                if (position != takePhotoEntities.size() - 1) {
                    //震动
                    TipHelper.Vibrate(ScanSealSignActivity.this, 500);
                    MyDialog deleteDialog = new MyDialog(ScanSealSignActivity.this);
                    deleteDialog.setIcon(R.drawable.alert);
                    deleteDialog.setMessage("确定删除该图片吗?");
                    deleteDialog.setPositiveClickListener("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            takePhotoEntities.remove(position);
                            pickPic.remove(position);
                            List<String> tempPickPic = new ArrayList<>();
                            tempPickPic.addAll(pickPic);
                            resetPicture(tempPickPic);
                        }
                    });
                    deleteDialog.setNegativeClickListener(R.drawable.btn_cancel_selector, "取消", null);
                    deleteDialog.show();
                }
            }
        });
        rvTakePhoto.setLayoutManager(new GridLayoutManager(this, 4));
        rvTakePhoto.setAdapter(takePhotoAdapter);

        //选择图片路径
        pickPic = new ArrayList<>();

        //初始化图片选择框架
        galleryConfig = new GalleryConfig.Builder()
                // 监听接口（必填）
                .iHandlerCallBack(iHandlerCallBack)
                // provider (必填)
                .imageLoader(new GlideImageLoader()).provider("com.yimi.yinhepda.fileprovider")
                // 记录已选的图片
                .pathList(pickPic)
                // 配置是否多选的同时 配置多选数量   默认：false
                .multiSelect(true, 4)
                // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(false)
                //设置水印
                .setWaterMask(true)
                //设置水印文字
                .setWaterMaskText(sharedPreferUtil.getEmpName() + " " + sharedPreferUtil.getWorkNum() + " 封")
                // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .crop(false, 1, 1, 500, 500)
                // 是否实现相机按钮  默认：false
                .isShowCamera(true)
                // 图片存放路径
                .filePath("/Gallery/Pictures").build();
    }

    /**
     * 图片加载框架，返回图接口
     */
    IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
        @Override
        public void onStart() {
            LogUtil.e("onStart: 开启");
        }

        @Override
        public void onSuccess(List<String> photoList) {
            LogUtil.e("onSuccess: 返回数据");
            for (String s : photoList) {
                LogUtil.e(s);
            }
            resetPicture(photoList);
        }

        @Override
        public void onCancel() {
            LogUtil.e("onCancel: 取消");
        }

        @Override
        public void onFinish() {
            LogUtil.e("onFinish: 结束");
        }

        @Override
        public void onError() {
            LogUtil.e("onError: 出错");
        }
    };

    private void resetPicture(final List<String> photoList) {
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                takePhotoEntities.clear();
                pickPic.clear();
                if (photoList != null && photoList.size() > 0) {
                    pickPic.addAll(photoList);
                }

                if (photoList != null) {
                    for (int i = 0; i < photoList.size(); i++) {
                        LogUtil.e(photoList.get(i));

                        Bitmap mBitmap = BitmapUtils.decodeSampledBitmapFromFile(photoList.get(i), 800, 1100);
                        BitmapUtils.compressBmpToFile(mBitmap, photoList.get(i));
                        takePhotoEntities.add(new TakePhotoEntity(mBitmap));
                    }
                }
                takePhotoEntities.add(new TakePhotoEntity(BitmapFactory.decodeResource(getResources(), R.drawable.btn_take_photo_selector)));

                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                takePhotoAdapter.notifyDataSetChanged();
                if (!isGalleryConfigPick) {
                    galleryConfig.getBuilder().pathList(pickPic);
                }
                isGalleryConfigPick = false;
            }

            @Override
            public void onError(Throwable throwable) {
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    private void checkPersmisson() {
        PermissionUtils.checkMorePermissions(this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
            @Override
            public void onHasPermission() {
                galleryConfig.getBuilder().isOpenCamera(false).build();
                galleryConfig.getBuilder().pathList(pickPic);
                GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(ScanSealSignActivity.this);
            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {
                PermissionUtils.requestMorePermissions(ScanSealSignActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                PermissionUtils.requestMorePermissions(ScanSealSignActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSIONS:
                PermissionUtils.onRequestMorePermissionsResult(ScanSealSignActivity.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
                    @Override
                    public void onHasPermission() {
                        galleryConfig.getBuilder().isOpenCamera(false).build();
                        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(ScanSealSignActivity.this);
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDown(String... permission) {
                        PermissionUtils.requestMorePermissions(ScanSealSignActivity.this, PERMISSIONS, REQUEST_CODE_PERMISSIONS);
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                        Common.showPermissionDialog(ScanSealSignActivity.this, "程序需要获取相机权限，才能继续使用，请去权限界面打开！", null);
                    }
                });
                break;
            default:
                break;
        }
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            doScan(result);
        }
    }

    /**
     * 处理扫描结果
     */
    private void doScan(String result) {
        if (!StringUtils.isSealsNO(result)) {
            showToast("封签号格式不正确！");
            SoundVibratorManager.playSound(2);
            return;
        }
        if (mScanSealSignEntities == null || mAdapter == null) {
            showToast("初始化程序失败，请退出重进！");
            return;
        }
        for (ScanSealSignEntity entity : mScanSealSignEntities) {
            if (entity.getSealSignNo().equals(result)) {
                SoundVibratorManager.playSound(2);
                showToast("该封签已扫描！");
                return;
            }
        }
        mScanSealSignEntities.add(new ScanSealSignEntity(result));
        mAdapter.notifyDataSetChanged();
        SoundVibratorManager.playSound(1);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_back:
                showBackDialog();
                break;
            case R.id.ib_delete:
                Iterator<ScanSealSignEntity> it = mScanSealSignEntities.iterator();
                while (it.hasNext()) {
                    ScanSealSignEntity entity = it.next();
                    if (entity.isCheck()) {
                        it.remove();
                    }
                }
                mAdapter.notifyDataSetChanged();
                SoundVibratorManager.playSound(1);
                break;
            case R.id.btn_sealCar:
                //装车类型：1-离线装车类型,2-离线卸车，3-单独封车
                if (loadType == 1 || loadType == 2 || loadType == 3) {
                    showOfflineSubmitDialog();
                } else {
                    //查询数据字典：强制封签拍照
                    queryDictValue();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 查询数据字典：强制封签拍照
     */
    private void queryDictValue() {
        showPgDlg("数据请求中...");
        Map<String, String> params = new HashMap<>();
        params.put("params", "fc_photograph");
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_QUERY_DICT_VALUE)
                .setParams(params)
                .setResponsClazz(QueryFCPhotographDictResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryFCPhotographDictResponse response = (QueryFCPhotographDictResponse) obj;
                        boolean hasDeptCode = false;
                        if (response.getData() != null) {
                            Map<String, String> maps = response.getData().getCoercePhotograph();
                            if (maps != null) {
                                for (String key : maps.keySet()) {
                                    String value = maps.get(key);
                                    String deptCode = sharedPreferUtil.getDeptCode();
                                    if (deptCode.equals(value)) {
                                        hasDeptCode = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if (hasDeptCode) {
                            if (pickPic == null || pickPic.isEmpty()) {
                                showToast("当前部门需添加照片上传");
                                return;
                            }
                        }
                        //校验是否有照片
                        checkHasPhoto();
                    }
                });
    }

    /**
     * 校验是否有照片
     */
    private void checkHasPhoto() {
//        if (takePhotoEntities == null || takePhotoEntities.size() < 3) {
//            // 2,3,4分别是一级网点，二级网点，三级网点; 5,6分别是一级分拨，二级分拨
//            int deptType = sharedPreferUtil.getIntValue(Common.DEPT_TYPE);
//            if(deptType == 5 || deptType == 6){
//                //获取分拨code，当前分拨code不在list中，做强制拍照上传
//                String currDeptCode = sharedPreferUtil.getDeptCode();
//                String[] deptCodes = getResources().getStringArray(R.array.dept_code);
//                boolean hasDeptCode = false;
//                for (String item : deptCodes) {
//                    if (currDeptCode.equals(item)) {
//                        hasDeptCode = true;
//                    }
//                }
//                if (!hasDeptCode) {
//                    //小于两张上传图片则提示
//                    showNoPhtotDialog();
//                    return;
//                }
//            }
//        }
        //在线装车封车提交
        submitFinishSealCar();
    }

    /**
     * 提示需拍照
     */
    private void showNoPhtotDialog() {
        MyDialog dialog = new MyDialog(this);
        dialog.setIcon(R.drawable.alert);
        dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
        dialog.setTitle("提示");
        dialog.setMessage("至少两张封车照片上传，请先拍照");
        dialog.setPositiveClickListener("拍照",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        galleryConfig.getBuilder().isOpenCamera(true).build();
                        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(ScanSealSignActivity.this);
                    }
                });
        dialog.setNegativeClickListener(R.drawable.btn_login_selector, "取消", null);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @Override
    public void onItemClickListener(int position) {
        mScanSealSignEntity = mScanSealSignEntities.get(position);
        if (mScanSealSignEntity.isCheck()) {
            mScanSealSignEntity.setCheck(false);
        } else {
            mScanSealSignEntity.setCheck(true);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemLongClickListener(int position) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            showBackDialog();
        }
        return false;
    }

    /**
     * 退出提示框
     */
    private void showBackDialog() {
        //装车类型：1-离线装车类型,2-离线卸车，3-单独封车
        if (loadType == 1 || loadType == 2) {
            MyDialog dialog = new MyDialog(this);
            dialog.setIcon(R.drawable.alert);
            dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
            dialog.setTitle("系统提示");
            if (loadType == 2) {
                dialog.setMessage("点击返回后将进入数据暂存列表，是否返回？");
            } else {
                dialog.setMessage("点击返回之前装车数据将进入数据暂存列表，是否返回？");
            }
            dialog.setPositiveClickListener("是",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                            if (loadType == 2) {
                                //跳转至离线卸车暂存界面
                                toActivity(OffLineUnLoadCacheActivity.class);
                            } else {
                                //跳转至离线装车暂存界面
                                toActivity(OffLineLoadCacheActivity.class);
                            }
                        }
                    });
            dialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", null);
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        } else {
            finish();
        }
    }

    /**
     * 离线装车封车提示框
     */
    private void showOfflineSubmitDialog() {
        if (mBizTypeCodes != null) {
            if (mBizTypeCodes.equals("1") && mScanSealSignEntities.isEmpty()) {
                if (loadType == 2) {
                    //离线卸车解封，为干线给出提示
                    final MyDialog dialog = new MyDialog(this);
                    dialog.setIcon(R.drawable.alert);
                    dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                    dialog.setTitle("系统提示");
                    dialog.setMessage("当前运输方式为干线，是否强制使用封签解封扫描？");
                    dialog.setPositiveClickListener("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialog.dismiss();
                        }
                    });
                    dialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //继续封签/解封
                            keepOnToSealSign();
                        }
                    });
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.show();
                } else {
                    //干线且无封签码，则提示
                    MyDialog.showAlertDialog(ScanSealSignActivity.this, "提示", "当前运输方式为干线，强制使用封签封车扫描。", "是");
                }
                return;
            }
        } else {
            showToast("未获取到运输方式！");
            return;
        }

        //继续封签/解封
        keepOnToSealSign();

    }

    /**
     * 继续封签/解封
     */
    private void keepOnToSealSign() {
        MyDialog dialog = new MyDialog(this);
        dialog.setIcon(R.drawable.alert);
        dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
        dialog.setTitle("系统提示");
        String messgae = "是否对车牌号：" + carPlateNo + "\n";
        //装车类型：1-离线装车类型,2-离线卸车，3-单独封车
        if (loadType == 2) {
            //离线卸车
            messgae += "进行车辆到车解封并进入卸车扫描界面？";
        } else {
            messgae += "离线封车发车并将数据保存至装车任务暂存集？";
        }
        dialog.setMessage(messgae);
        dialog.setPositiveClickListener("是",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        UnloadTaskTableDao unloadTaskTableDao = new UnloadTaskTableDao();
                        UnloadTaskTable unloadTaskTable = unloadTaskTableDao.findData(offlineTaskNo, sharedPreferUtil.getValue(Common.USER_CODE));
                        if (unloadTaskTable != null) {
                            dialog.dismiss();
                            String sealSignNOs = "";
                            for (ScanSealSignEntity entity : mScanSealSignEntities) {
                                sealSignNOs += entity.getSealSignNo() + ",";
                            }
                            if (sealSignNOs.length() > 1) {
                                sealSignNOs = sealSignNOs.substring(0, sealSignNOs.length() - 1);
                            }
                            unloadTaskTable.setSealSignNo(sealSignNOs);
                            //设置封车/解封时间
                            unloadTaskTable.setSealSignTime(DateHelper.getDateTimeFormateForSimple(new Date()));
                            //装车类型：1-封车，2-未封车，3-卸车，4-未卸车，5-已解封，6-单独封车
                            if (loadType == 2) {
                                unloadTaskTable.setLoadType(5);
                            } else {
                                unloadTaskTable.setLoadType(1);
                            }
                            try {
                                unloadTaskTableDao.update(unloadTaskTable);
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                            finish();
                            if (loadType == 2) {
                                //跳转至离线卸车扫描界面
                                Intent intent = new Intent(ScanSealSignActivity.this, OffLineUnloadActivity.class);
                                intent.putExtra("offlineTaskNo", offlineTaskNo);
                                startActivity(intent);
                            } else {
                                //跳转至离线装车任务暂存集
                                toActivity(OffLineLoadCacheActivity.class);
                            }
                        } else {
                            showToast("未查询到离线任务配载单！");
                        }
                    }
                });
        dialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", null);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 提交完成封车
     */
    private void submitFinishSealCar() {
        String stowageNo = "";
        String carNo = "";
        String nextStationCode = "";
        String nextStation = "";
        String bizTypeCode = "";
        String url = Constants.URL_V2_START_SEAL_CAR;

        //判断是否车线任务
        if (mCarPlanTaskEntityList != null) {
            for (CarPlanTaskEntity planTask : mCarPlanTaskEntityList) {
                if (planTask.getBeTask() == 1) {
                    //车线任务，直接提示封车
                    showSealSignDialog(new SelectSealSignStowage(planTask.getTaskNo(), nextStationCode, nextStation, carNo, 0), url);
                    return;
                }
            }
        }

        if (!mFromSetOutActivity) {

            if (mStowageNos == null || mStowageNos.length() == 0) {
                showToast("无封车的配载单！");
                return;
            }
            String[] stowageNoSplit = mStowageNos.split("/");
            String[] carNoSplit = mCarNos.split("/");
            String[] nextStaCodeSplit = mNextStationCodes.split("/");
            String[] nextStationSplit = mNextStation.split("/");
            String[] bizTypeCodeSplit = mBizTypeCodes.split("/");
            if (stowageNoSplit != null && stowageNoSplit.length > 1) {
                final List<SelectSealSignStowage> sealSignStowageList = new ArrayList<>();
                for (int i = 0; i < stowageNoSplit.length; i++) {
                    String temStowNo = "";
                    try {
                        temStowNo = stowageNoSplit[i];
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String tempNextCode = "";
                    try {
                        tempNextCode = nextStaCodeSplit[i];
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String tempNextName = "";
                    try {
                        tempNextName = nextStationSplit[i];
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String tempCarNo = "";
                    try {
                        tempCarNo = carNoSplit[i];
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    int tempBizTypeCode = 0;
                    try {
                        tempBizTypeCode = Integer.parseInt(bizTypeCodeSplit[i]);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }

                    boolean hasStowage = false;
                    for (String stowNo : mStowageNoList) {
                        if (stowNo.equals(temStowNo)) {
                            hasStowage = true;
                        }
                    }
                    if (!hasStowage) {
                        sealSignStowageList.add(new SelectSealSignStowage(temStowNo, tempNextCode, tempNextName, tempCarNo, tempBizTypeCode));
                    }
                }

                if (sealSignStowageList.size() == 1) {
                    showSubmitDialog(sealSignStowageList.get(0), url);
                    return;
                }

                //弹出对话框选择配载单
                LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.alert_dialog_select_stowage_no, null);
                mSelectStowageDialog = new Dialog(this, R.style.AsyncTaskDialog);
                RecyclerView rvSelectList = layout.findViewById(R.id.lv_selectStowageNo);
                mSelectStowageDialog.addContentView(layout,
                        new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                mSelectStowageDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                mSelectStowageDialog.getWindow().getDecorView().setPadding(10, 0, 10, 0);
                mSelectStowageDialog.show();
                final String finalUrl = url;
                SelectSealSignStowageAdapter adapter = new SelectSealSignStowageAdapter(this, sealSignStowageList,
                        new CommonViewHolder.onItemCommonClickListener() {
                            @Override
                            public void onItemClickListener(int position) {
                                showSubmitDialog(sealSignStowageList.get(position), finalUrl);
                            }

                            @Override
                            public void onItemLongClickListener(int position) {
                            }
                        });
                rvSelectList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                rvSelectList.setAdapter(adapter);
                return;
            } else if (stowageNoSplit != null && stowageNoSplit.length == 1) {
                //获取车牌号
                if (stowageNoSplit.length > 0) {
                    stowageNo = stowageNoSplit[0];
                }
                //获取车牌号
                if (carNoSplit.length > 0) {
                    carNo = carNoSplit[0];
                }
                //获取下一站code
                if (nextStaCodeSplit.length > 0) {
                    nextStationCode = nextStaCodeSplit[0];
                }
                //获取下一站名称
                if (nextStationSplit.length > 0) {
                    nextStation = nextStationSplit[0];
                }
                //获取运输方式
                if (bizTypeCodeSplit.length > 0) {
                    bizTypeCode = bizTypeCodeSplit[0];
                }
            }
        } else {
            //出发封车界面传过来的数据
            CarPlanTaskEntity planTask = mCarPlanTaskEntityList.get(0);
            stowageNo = planTask.getTaskNo();
            carNo = planTask.getVehNo();
            nextStationCode = planTask.getLoadTasks().get(0).getDestDeptCode();
            bizTypeCode = String.valueOf(planTask.getLoadTasks().get(0).getBizTypeCode());
        }

        if (stowageNo.startsWith("P")) {
            //快运配载单
            //配载单查询是否配载数据，未配载不可封车
            showSubmitDialog(new SelectSealSignStowage(stowageNo, nextStationCode, nextStation, carNo, Integer.parseInt(bizTypeCode)), url);
        } else {
            //快递配载单，直接提示封车
            showSealSignDialog(new SelectSealSignStowage(stowageNo, nextStationCode, nextStation, carNo, Integer.parseInt(bizTypeCode)), url);
        }
    }

    /**
     * 配载单查询是否配载数据，未配载不可封车
     */
    private void showSubmitDialog(final SelectSealSignStowage selectSealSignStowage, final String url) {
        showPgDlg("查询数据中...");
        //校验配载单是否配载数据，没有配载提示用户无不能封车
        QueryLoadDetailRequest mQueryLoadDetailRequest = new QueryLoadDetailRequest();
        mQueryLoadDetailRequest.setStowageNo(selectSealSignStowage.getStowageNo());
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(QueryLoadDetailResponse.class)
                .setUrl(Constants.QUERY_LOADDATA)
                .setRequestObject(mQueryLoadDetailRequest)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        //装车数据
                        QueryLoadDetailResponse response = (QueryLoadDetailResponse) obj;
                        List<QueryLoadDetailBillcode> loadDataEntityList = response.getData();
                        boolean hasScan = false;
                        if (loadDataEntityList != null) {
                            for (QueryLoadDetailBillcode entity : loadDataEntityList) {
                                boolean isBreak = false;
                                for (QueryLoadDetailChildBillcode childEntity : entity.getChildList()) {
                                    if (childEntity.getFlag() == 1) {
                                        hasScan = true;
                                        isBreak = true;
                                        break;
                                    }
                                    if (isBreak) {
                                        break;
                                    }
                                }
                            }
                        }
                        if (!hasScan) {
                            //无扫描运单，不能封车
                            MyDialog.showAlertDialog(ScanSealSignActivity.this, "提示", "配载单：" + selectSealSignStowage.getStowageNo() + "未配货，不能封车", "确定");
                        } else {
                            //有扫描的运单可封车
                            showSealSignDialog(selectSealSignStowage, url);
                        }
                    }
                });
    }

    /**
     * 封车完成提示框
     */
    private void showSealSignDialog(final SelectSealSignStowage selectSealSignStowage, final String url) {
        if (this.isFinishing()) {
            showToast("提示框未能展示，请退出重试！");
            return;
        }
        String msg = "任务号：" + selectSealSignStowage.getStowageNo() + "\n是否封车完成？";
        //封车
        MyDialog dialog = new MyDialog(this);
        dialog.setIcon(R.drawable.alert);
        dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
        dialog.setTitle("提示");
        dialog.setMessage(msg);
        dialog.setPositiveClickListener("是",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        List<String> sealNos = new ArrayList<>();
                        for (int i = 0; i < mScanSealSignEntities.size(); i++) {
                            sealNos.add(mScanSealSignEntities.get(i).getSealSignNo());
                        }
                        //干线：强制扫描封签进行封车操作。如遇未扫描封签点击解封弹出提示
                        if (selectSealSignStowage.getBizTypeCodes() == 1 && mScanSealSignEntities.isEmpty()) {
                            MyDialog.showAlertDialog(ScanSealSignActivity.this, "提示", "当前运输方式为干线，强制使用封签封车扫描。", "是");
                        } else {
                            submitNetRequest(selectSealSignStowage, sealNos, url);
                        }
                    }
                });
        dialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", null);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 封车网络请求
     */
    private void submitNetRequest(final SelectSealSignStowage selectSealSignStowage, final List<String> sealNos, final String url) {
        //上传图片获取key
        if (pickPic != null && !pickPic.isEmpty()) {
            showPgDlg("正在上传图片数据...");
            Map param = new HashMap();
            //4为图片上传格式规范ID，8为视频上传规范ID
            param.put("uploaderStrategyId", "4");

            NetRequest request = new NetRequest();
            for (int i = 0; i < pickPic.size(); i++) {
                String item = pickPic.get(i);
                String fileName = item.substring(item.lastIndexOf("/") + 1);
                request.addFile("file" + i, fileName, new File(item));
            }
            request.setParams(param)
                    .setMethod(NetRequest.Method.POST)
                    .setUrl(Constants.URL_UPLOAD_IMAGE)
                    .setResponsClazz(ImageInfoResponse.class)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            setScannerEnabled(true);
                            dismissPgDlg();
                            SoundVibratorManager.playSound(2);
                            if (msg != null) {
                                showToast("上传图片失败:" + msg);
                            } else {
                                showToast("上传图片失败!");
                            }
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            ImageInfoResponse response = (ImageInfoResponse) obj;
                            imageKey = "";
                            for (ImageInfo item : response.getData()) {
                                imageKey += (item.getFileKey() + ",");
                            }
                            imageKey = imageKey.substring(0, imageKey.length() - 1);
                            submitData(selectSealSignStowage, sealNos, url);
                        }
                    });
        } else {
            submitData(selectSealSignStowage, sealNos, url);
        }
    }

    private void submitData(final SelectSealSignStowage selectSealSignStowage, List<String> sealNos, String url) {

        final SetOutSealCarRequest setOutSealCarRequest = new SetOutSealCarRequest();
        if (mCarPlanTaskEntityList != null) {
            for (CarPlanTaskEntity planTask : mCarPlanTaskEntityList) {
                if (planTask.getBeTask() == 1) {
                    if(planTask.getTaskNo().equals(selectSealSignStowage.getStowageNo())){
                        setOutSealCarRequest.setTaskNo(planTask.getTaskNo());
                        if (planTask.getNextDeptCode() != null) {
                            setOutSealCarRequest.setDestDeptCode(planTask.getNextDeptCode());
                        } else if (planTask.getVehLineCode() != null) {
                            String[] lineCodeSplit = planTask.getVehLineCode().split("-");
                            String currentDeptCode = sharedPreferUtil.getDeptCode();
                            //截取车线任务线路的下一站编码
                            int nextDeptIndex = -1;
                            for (int i = 0; i < lineCodeSplit.length; i++) {
                                if (currentDeptCode.equals(lineCodeSplit[i])) {
                                    nextDeptIndex = i + 1;
                                    if (nextDeptIndex > 0 && nextDeptIndex <= lineCodeSplit.length - 1) {
                                        setOutSealCarRequest.setDestDeptCode(lineCodeSplit[nextDeptIndex]);
                                        break;
                                    } else {
                                        showToast("未截取到车线下一站！");
                                        return;
                                    }
                                }
                            }
                        } else {
                            showToast("线路编码为空！");
                            return;
                        }
                    }
                } else {
                    if(planTask.getLoadTasks() != null){
                        for (LoadBillTaskEntity loadTask : planTask.getLoadTasks()) {
                            if (loadTask.getStowageNo().equals(selectSealSignStowage.getStowageNo())) {
                                setOutSealCarRequest.setDestDeptCode(loadTask.getDestDeptCode());
                                setOutSealCarRequest.setTaskNo(loadTask.getStowageNo());
                            }
                        }
                    }
                }
                setOutSealCarRequest.setBeTask(planTask.getBeTask());
            }
        }
        setOutSealCarRequest.setSrcDeptCode(sharedPreferUtil.getDeptCode());
        setOutSealCarRequest.setSealNos(sealNos);
        setOutSealCarRequest.setOperateTime(DateHelper.getDateTimeFormate(new Date()));
        setOutSealCarRequest.setFileIds(imageKey);
        showPgDlg("上传封车数据中...");
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(Object.class)
                .setUrl(url)
                .setRequestObject(setOutSealCarRequest)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        MyDialog.showAlertDialog(ScanSealSignActivity.this, "提示", msg, "确定");
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        showToast("封车成功！");

                        //更新本地暂存装车任务状态为已完成
                        LoadUtil.updateStatusForLoad(setOutSealCarRequest.getTaskNo());

                        mStowageNoList.add(selectSealSignStowage.getStowageNo());
                        if (mSelectStowageDialog != null && mSelectStowageDialog.isShowing()) {
                            mSelectStowageDialog.dismiss();
                        }
                        mScanSealSignEntities.clear();
                        mAdapter.notifyDataSetChanged();
                        pickPic.clear();
                        takePhotoEntities.clear();
                        takePhotoEntities.add(new TakePhotoEntity(BitmapFactory.decodeResource(getResources(), R.drawable.btn_take_photo_selector)));
                        takePhotoAdapter.notifyDataSetChanged();
                        for (BaseActivity activity : ActivityStack.getInstance().getActivities()) {
                            if (activity instanceof SetOutSealCarActivity) {
                                activity.finish();
                            }
                            if (activity instanceof NewLoadTaskActivity) {
                                activity.finish();
                            }
                            if (activity instanceof LoadScanActivity) {
                                activity.finish();
                            }
                            if (activity instanceof LoadSuccessActivity) {
                                activity.finish();
                            }
                        }
                        SoundVibratorManager.playSound(1);
                        finish();
                        //发送消息给首页处理待办事项数据，将完成的数据清除
                        LoadUtil.sendEventToSouYe(3, setOutSealCarRequest.getTaskNo(), null);
                    }
                });
    }
}
